import { ElMessage } from 'element-plus';

let checkConnetTimer: NodeJS.Timeout | null;
let webSocket: WebSocket | null;
let connectStatus = false;
const socketUrl = 'ws://www.linxyun.com:9528'; // websocket 连接url
export const ws = {
	init: function () {
		this.onOpen(); //  打开连接
		this.onClose(); //  监听连接是否关闭
		this.onError(); // 监听连接错误
		this.recvData(); // 接收数据
		// this.connect(); // 连接
	},

	/**
	 * 打开连接
	 */
	onOpen: function (UserID: string, isGroup: boolean = false) {
		const that = this;
		webSocket?.addEventListener('open', () => {
			console.log('WebSocket 已连接', webSocket?.readyState);
			connectStatus = true; //将连接状态设成true
			const timestamp = parseInt(Date.now() / 1000 + '');
			console.log('onOpen timestamp : ' + timestamp);
			localStorage.setItem('wsRecvDataTime', timestamp + '');

			clearInterval(checkConnetTimer!);
			checkConnetTimer = null; // 连接时清除上一个定时器

			// const UserID = localStorage.getItem('chatUserID');
			if (!UserID) return ElMessage.error('UserID为空');
			// 发送心跳
			const params: Record<string, any> = {};
			params.optype = 'req';
			params.type = 'HB';
			params.userid = UserID;
			that.sendHBMsg(params);

			// 发送进入通知
			console.log('isGroup', isGroup);
			if (isGroup) {
				const onShow: Record<string, any> = {};
				onShow.optype = 'notify';
				onShow.type = 'onShow';
				onShow.Recver = BASE_API.ENT_CODE;
				onShow.MsgClassify = 1;
				onShow.to_key = BASE_API.ENT_CODE;
				onShow.to_subkey = '_Any_';
				onShow.Sender = UserID;
				that.send(onShow);
			}
		});
	},

	/**
	 * 连接关闭
	 */
	onClose: function () {
		const that = this;
		webSocket?.addEventListener('close', () => {
			console.log('已断开连接');
			connectStatus = false;
		});
	},

	resetSocket: function () {
		// 重置webSocket，不关闭心跳定时器
		webSocket?.close();
		console.log('webSocket重置成功');
		webSocket = null;
		connectStatus = false;
	},

	closeWebSocket: function () {
		// 手动关闭webSocket
		const that = this;
		webSocket?.close();
		console.log('webSocket关闭成功');
		webSocket = null;
		connectStatus = false;
		console.log('清空心跳');
		clearInterval(checkConnetTimer!);
		checkConnetTimer = null;
		localStorage.removeItem('wsRecvDataTime');
		setTimeout(() => {
			that.connect();
		}, 1000);
	},

	/**
	 * 连接错误
	 */
	onError: function () {
		const that = this;
		webSocket?.addEventListener('error', (e) => {
			connectStatus = false;
			console.error('socket error: ', e);
			webSocket?.close();
		});
	},

	/**
	 * 接收数据
	 */
	recvData: function (callback?: (message) => void) {
		webSocket?.addEventListener('message', (event) => {
			// console.log('socket message:', event);
			//数据处理。方便界面中处理数据
			var timestamp = parseInt(Date.now() / 1000 + '');
			localStorage.setItem('wsRecvDataTime', timestamp + '');
			// if(JSON.parse(message.data).type == 'HB'){
			//   return
			// }
			callback && callback(event);
		});
	},

	/**
	 * 连接
	 */
	connect: function (UserID: string) {
		// clearInterval(checkConnetTimer)
		// checkConnetTimer = null // 连接时清除上一个定时器
		connectStatus = false; //将连接状态设成false
		// const UserID = localStorage.getItem('chatUserID');
		const EntCode = BASE_API.ENT_CODE;
		const url = socketUrl;
		// if (!UserID) return ElMessage.error('UserID为空');
		if (!EntCode) return ElMessage.error('EntCode为空');
		if (!url) return ElMessage.error('socketUrl为空');
		console.log('socketUrl : ' + url);
		// '/websocket/onOpen.ws?c_key=' + EntCode + '#000&c_subkey=' + UserID;
		// const connectUrl = url + '/websocket/onOpen.ws?c_key=' + EntCode + '%23000&c_subkey=' + UserID;
		const connectUrl = url + '/websocket/onOpen.ws?c_key=' + EntCode + '&c_subkey=' + UserID;

		console.log(connectUrl);
		webSocket = new WebSocket(connectUrl);
		console.log('ws 连接状态：', webSocket.readyState);
	},

	/**
	 * 发送指令
	 */
	send: function (params: Record<string, any>) {
		const that = this;
		if (webSocket?.readyState !== 1) {
			return;
		}
		console.log(params, 'sendMsg');
		webSocket?.send(JSON.stringify(params));
	},

	sendHBMsg(params: Record<string, any>) {
		const that = this;
		if (webSocket?.readyState !== 1) {
			return;
		}
		checkConnetTimer = setInterval(() => {
			if (connectStatus) {
				const timestamp = parseInt(Date.now() / 1000 + '');
				console.log('sendHBMsg timestamp : ' + timestamp);
				if (localStorage.getItem('wsRecvDataTime')) {
					const lasttime = Number(localStorage.getItem('wsRecvDataTime'));
					console.log('wsRecvDataTime: ' + lasttime);
					if (timestamp - lasttime! > 12) {
						that.resetSocket();
						return;
					}
				}
				webSocket?.send(JSON.stringify(params));
			} else {
				that.connect();
			}
		}, 1000 * 5);
	},
};

// webScoket.init();
